package com.tbit.uqbike.tergateway.entity;

import com.tbit.uqbike.protocol.AnalyzeImpl.TurnDeEnCoder;
import com.tbit.uqbike.tergateway.data.TerGatewayData;
import com.tbit.uqbike.util.CharsetName;
import com.tbit.uqbike.util.ProtocolUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;

/**
 * Created by MyWin on 2018/6/26 0026.
 */
public class ConnInfoTurn extends AConnInfo {
    public String terConnId;//终端实际连接ID，当协议名称是转发协议的时候有效
    public String mainConnId;//转发连接ID，当协议名称是转发协议的时候有效

    public ConnInfoTurn(String terConnId, String mainConnId) {
        this.terConnId = terConnId;
        this.mainConnId = mainConnId;
        this.connId = String.format("%s.%s", this.mainConnId, this.terConnId);
    }

    @Override
    public ChannelHandlerContext getCtx() {
        ChannelHandlerContext ctx = null;
        AConnInfo info = TerGatewayData.GetConnect(this.mainConnId);
        if (null != info) {
            ctx = info.getCtx();
        }
        return ctx;
    }

    @Override
    public boolean downMsg(ByteBuf byteBuf) {
        try {
            try {
                if (null == byteBuf || byteBuf.readableBytes() == 0) {
                    return false;
                }
                // 构造转发协议
                ByteBuf turnBuf = PooledByteBufAllocator.DEFAULT.directBuffer();
                // 此处注意需要释放掉临时变量 byteBuf，不然会内存泄露
                turnBuf.writeBytes(TurnDeEnCoder.PRO_HEAD);
                turnBuf.writeByte(1);
                turnBuf.writeByte(0);
                byte[] connIdBs = terConnId.getBytes(CharsetName.US_ASCII);
                turnBuf.writeInt(1 + connIdBs.length + 4 + byteBuf.readableBytes());
                turnBuf.writeByte(connIdBs.length);
                turnBuf.writeBytes(connIdBs);
                turnBuf.writeInt(byteBuf.readableBytes());
                turnBuf.writeBytes(byteBuf);
                // crc
                int crc = ProtocolUtil.GetCrcByteArray(turnBuf, 2, turnBuf.readableBytes() - 2);
                turnBuf.writeShort(crc);
                ChannelHandlerContext ctx = getCtx();
                if (null != ctx) {
                    ctx.writeAndFlush(turnBuf);
                    return true;
                }
            } catch (Exception e) {

            } finally {
                if (null != byteBuf) {
                    byteBuf.release();
                }
            }
        } catch (Exception e) {

        }
        return false;
    }

    @Override
    public void closeConn() {

    }
}
